package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class  EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //加密后会得到一个16进制的字符串

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /*
        新增员工
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
        //1.将接受过来的DTO数据封装到Entity中
        Employee employee = new Employee();

        //原始方式将dto数据一个一个设置到entity非常低效
          //比如：employee.setName(employeeDTO.getName());
        //BeanUtils可以用来做对象属性的拷贝（前提是属性要对应）
        BeanUtils.copyProperties(employeeDTO,employee);

        //2.完善employee中属性：默认密码、状态，创建时间，更新时间，创建和更新的用户
        //默认密码                     PasswordConstant.DEFAULT_PASSWORD定义好的一个常量
        String mdgPwd = DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes());
        employee.setPassword(mdgPwd);
        //状态            StatusConstant.ENABLE也是定义好的常量
        employee.setStatus(StatusConstant.ENABLE);
        //创建时间
        employee.setCreateTime(LocalDateTime.now());
        //修改时间
        employee.setUpdateTime(LocalDateTime.now());

    //快捷键：
        //Ctrl+Alt+V:抽取表达式为局部变量

        //从线程局部变量中获取empId
        Long currentId = BaseContext.getCurrentId();
        //创建用户
        employee.setCreateUser(currentId);
        //修改用户
        employee.setUpdateUser(currentId);

        //3.调用mapper层，把employee插入到数据库中
        employeeMapper.save(employee);

    }

    //分页查询
    @Override
    public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
        //1.基于分页插件实现动态分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
          Page<Employee> pages = employeeMapper.page(employeePageQueryDTO);

          //封装PageResult返回回去
          return new PageResult(pages.getTotal(),pages.getResult());
    }


    //启用或者禁用员工账号
    @Override
    public void startOrStop(Integer status, Long id) {
        //修改员工的状态，构建表的实体映射对象 Employee
        Employee employee = Employee.builder()
                .id(id)
                .status(status)
                .build();
        //调用mapper层去更新
        employeeMapper.update(employee);
    }


    //根据id查询数据
    @Override
    public Employee getById(Long id) {
        //调用mapper查询指定id的员工数据
      Employee employee = employeeMapper.getById(id);

      //为了安全起见，需要把密码换成无意义的字符串
        employee.setPassword("***********");
        return employee;
    }


    /**
     * 编辑员工信息
     *
     * @param employeeDTO
     */
    @Override
    public void updateDTO(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }

}
